import type { Employee, AttendanceRecord, PayrollRecord } from '../types';

const BASE_URL = 'http://127.0.0.1:3001/api';

async function request(endpoint: string, options: RequestInit = {}) {
  const response = await fetch(`${BASE_URL}${endpoint}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
  });

  if (!response.ok) {
    if (response.status === 401) {
        // Handle unauthorized access, maybe redirect to login
        console.error("Unauthorized request. Redirecting to login.");
        // window.location.href = '/login'; // This might be too aggressive, handle in component
    }
    const errorData = await response.json().catch(() => ({ message: 'An unknown error occurred' }));
    throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
  }
  
  if (response.headers.get("Content-Length") === "0" || response.status === 204) {
      return null;
  }

  return response.json();
}

// --- Auth ---
export const login = (username: string, password: string): Promise<{ isAuthenticated: boolean; username?: string }> => {
  return request('/login', {
    method: 'POST',
    body: JSON.stringify({ username, password }),
  });
};

export const logout = (): Promise<{ message: string }> => {
  return request('/logout', { method: 'POST' });
};

export const checkAuth = (): Promise<{ isAuthenticated: boolean; username?: string }> => {
  return request('/check_auth');
};

// --- Employees ---
export const getEmployees = (): Promise<Employee[]> => {
  return request('/employees');
};

export const addEmployee = (employeeData: Omit<Employee, 'id' | 'avatar'>): Promise<{ id: number }> => {
  return request('/employees', {
    method: 'POST',
    body: JSON.stringify(employeeData),
  });
};

export const updateEmployee = (id: number, employeeData: Partial<Employee>): Promise<{ message: string }> => {
  return request(`/employees/${id}`, {
    method: 'PUT',
    body: JSON.stringify(employeeData),
  });
};

export const deleteEmployee = (id: number): Promise<{ message: string }> => {
  return request(`/employees/${id}`, {
    method: 'DELETE',
  });
};

// --- Attendance ---
export const getAttendance = (): Promise<AttendanceRecord[]> => {
  return request('/attendance');
};

// --- Payroll ---
export const getPayroll = (): Promise<PayrollRecord[]> => {
  return request('/payroll');
};
